package de.bht.cge.flightsim.gfx;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.bht.jvr.core.ShaderMaterial;
import de.bht.jvr.core.ShaderProgram;
import de.bht.jvr.core.Texture2D;
import de.bht.jvr.core.pipeline.Pipeline;
import de.bht.jvr.core.uniforms.UniformInt;
import de.bht.jvr.core.uniforms.UniformVector2;
import de.bht.jvr.math.Vector2;

public class TextOverlay 
{
    private float gridSize = 0.0625f;   
    private Vector2 position;
    private Vector2 size;
    private Texture2D tex;
    private ShaderMaterial material;
    private boolean initialized = false; 
    private FontMap map;
    
	public TextOverlay(float gridSize, Vector2 position, Vector2 size, String texPath)
	{
	    try
	    {
    	    this.tex = new Texture2D(new File(texPath));
    		this.gridSize = gridSize;
    		this.position = position;
    		this.size = size;
    		
    		this.map = FontMap.Default();
    		
    		ShaderProgram prog = new ShaderProgram(new File("shaders/overlay/textoverlay.vs"), new File("shaders/overlay/textoverlay.fs"));
            this.material = new ShaderMaterial("OVERLAY", prog);
            this.material.setTexture("OVERLAY", "jvr_Texture0",this.tex);
            this.material.setMaterialClass("Overlay");
	    }
	    catch(Exception e)
	    {
	        e.printStackTrace();
	    }
	}
	
		
    public void SetScreenText(String text,Pipeline p)
    {
        List<Vector2> letters = new ArrayList<Vector2>();
        List<Vector2> positions = new ArrayList<Vector2>();
        List<Vector2> size = new ArrayList<Vector2>();

        for(int i=0; i<text.length(); i++)
        {
            Character letter = new Character(text.charAt(i));
            Vector2 letterV = this.map.Get(letter);

            if(letterV != null)
            {
                letterV = letterV.mul(this.gridSize);
                letters.add(letterV);
                
                positions.add(new Vector2(((letters.size() - 1)) * this.size.x() + this.position.x(), this.position.y()));
                size.add(new Vector2(this.size.x(), this.size.y()));
            }
        }
        
        this.material.setUniform("OVERLAY", "lettersCount", new UniformInt(letters.size()));
        this.material.setUniform("OVERLAY", "letters", new UniformVector2(letters));
        this.material.setUniform("OVERLAY", "positions", new UniformVector2(positions));
        this.material.setUniform("OVERLAY", "size", new UniformVector2(size));  
        
        if(!this.initialized)
        {
            p.drawQuad(this.material, "OVERLAY");
            this.initialized = true;
        }
        
    }

}
